#include"Grammar.h"
using namespace std;
void Grammar::writetofile(string filename){
  ofstream fout;
  fout.open(filename.c_str());
  if(!fout.is_open()){
    cerr<<"Can not open file "<<filename<<endl;
    return;
  }
  fout<<"GrammarNumber\t"<<Grammar_Num<<endl;
  fout<<"TokenNumber\t"<<Token_Num<<endl;
  for(int i=0;i<Grammar_Num;i++)fout<<gs[i];
}
int intfromline(string line){
  istringstream cins(line);
  string temp;
  int v;
  cins>>temp;
  cins>>v;
  return v;
}
void Grammar::readfromfile(string filename){
  ifstream fin;
  fin.open(filename.c_str());
  if(fin.is_open()==false){
    cerr<<"Can not open file "<<filename<<endl;
    return ;
  }
  string line;
  getline(fin,line);//GrammarNumber
  Grammar_Num=intfromline(line);
  
  getline(fin,line);//TokenNumber
  Token_Num=intfromline(line);

  gs=new GrammarSymbol[Grammar_Num];
  for(int i=0;i<Grammar_Num;i++)fin>>gs[i];
}
inline double nextdouble(){
  return (rand()+1.0)/RAND_MAX;
}
void Grammar::initialize(int g_num,int t_num){
  cout<<"initialieze"<<endl;
  Grammar_Num=g_num;
  Token_Num=t_num;
  gs=new GrammarSymbol[g_num];
  
  srand(time(NULL));
  
  for(int i=0;i<Grammar_Num;i++){
    double tempv;
   
    gs[i].setg_num(Grammar_Num);
    gs[i].sett_num(Token_Num);
    //type rule
    tempv=nextdouble();
    gs[i].settype_e(tempv);
    gs[i].settype_b(1-tempv);
    
    //binary rule
    for(int j=0;j<Grammar_Num;j++)
      for(int k=0;k<Grammar_Num;k++)
	gs[i].setbinary(j,k,nextdouble());
    
    //emission rule
    for(int j=0;j<Token_Num;j++)
      gs[i].setemission(j,nextdouble());
  }
}
